#pragma once
#include "EventTypes.h"
#include <QObject>
#include <QThread>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <unordered_map>
#include <vector>

class EventEngine : public QObject {
    Q_OBJECT
public:
    using EventHandler = std::function<void(const Event&)>;
    
    static EventEngine* instance();
    
    // 启动事件引擎
    void start();
    
    // 停止事件引擎
    void stop();
    
    // 注册事件处理器
    void registerHandler(EventType type, const EventHandler& handler);
    
    // 取消注册事件处理器
    void unregisterHandler(EventType type);
    
    // 投递事件
    void postEvent(Event&& event);
    
    // 获取队列大小
    size_t queueSize() const;
    
    // 检查是否正在运行
    bool isRunning() const { return m_running; }
    
signals:
    void started();
    void stopped();
    
private:
    EventEngine(QObject* parent = nullptr);
    ~EventEngine();
    
    // 禁止拷贝和赋值
    EventEngine(const EventEngine&) = delete;
    EventEngine& operator=(const EventEngine&) = delete;
    
private slots:
    void processEvents();
    void timerThread();
    
private:
    std::queue<Event> m_eventQueue;
    mutable std::mutex m_queueMutex;
    std::condition_variable m_condition;
    
    std::unordered_map<EventType, std::vector<EventHandler>> m_handlers;
    mutable std::mutex m_handlerMutex;
    
    bool m_running{false};
    QThread m_eventThread;
    QThread m_timerThread;
};

#define EVENT_ENGINE EventEngine::instance() 